<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page import="java.io.*,java.sql.*,java.util.*,java.net.*,java.text.*"%>
<%@ page import="com.yuxin.common.util.*" %>
<%@ page import="com.yuxin.core.exception.SiteRuntimeException" %>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%
    Connection conn = DBUtil.getConnection();
    try{
        // 页面标题
        request.setAttribute("titleName","购物车");
        Map<String,Object> customer = null;
        //查询站点设置里应用设置的值
       	String url = "";
        boolean isLoginValid = CommonUtil.isLoginValid(request);
        if(!isLoginValid){//登录
            url = request.getContextPath()+"/site/denglu.jsp?url="+URLEncoder.encode(request.getContextPath()
                    + "/site/gouwuche.jsp", "UTF-8");
        }
        // 获取登录客户信息
        if(isLoginValid){
           customer = CommonUtil.getLoginUserInfo(request);
	    }
   		if(!CollectionUtils.isEmpty(customer)){
   	       	request.setAttribute("customer",customer);
   		}else{
   	       	request.setAttribute("customer","");
   		}
       	String productStr = URLDecoder.decode(StringUtils.getText(CommonUtil.getCookie(request,"productList")),"UTF-8");
       	String proIds = "";
        List<Map<String,Object>> contentList = new ArrayList<Map<String,Object>>();
       	if(StringUtils.hasText(productStr)){
       		Map productListMap = JsonUtil.json2map(productStr);
       		if(!CollectionUtils.isEmpty(productListMap)){
       			Set set = productListMap.keySet();
       			Iterator it = set.iterator();
       			while(it.hasNext()){
       				String proId = it.next().toString();
       				if(StringUtils.hasText(proIds)){
           				proIds += ",'"+proId+"'";
       				}else{
       					proIds = "'"+proId+"'";
       				}
       			}
       			request.setAttribute("productListMap",productListMap);
       		}
    		if(StringUtils.hasText(proIds)){
    	       	String proSql = "SELECT * FROM P_GOODS WHERE ID IN ("+proIds+") ORDER BY CREATE_TIME" ;
    	       	List<Map<String,Object>> list = DBUtil.queryList(conn,proSql);
    	       	List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();
    	       	for(int i=0;i<list.size();i++){
    	       		Map<String,Object> m = list.get(i);
	      	       	m.put("TOTAL",productListMap.get(m.get("ID")));
	      	        dataList.add(m);
    	       	}
    	       	request.setAttribute("dataList",dataList);
    		}
       	}
        request.setAttribute("url",url);
    }catch (Exception e){
        e.printStackTrace();
        throw new SiteRuntimeException(e);
    }finally {
        DBUtil.close(conn);
    }
%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>${titleName}</title>
    <meta name="Keywords" content="中信信用卡平台" />
    <meta name="Description" content="${titleName}"/>
    <meta name="robots" content="all"/>
    <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="apple-mobile-web-app-capable" content="yes"/>
    <meta name="apple-mobile-web-app-status-bar-style" content="black"/>
    <meta name="format-detection" content="telephone=no"/>
    <meta http-equiv="cleartype" content="on"/>
    <link rel="icon" type="image/png" href="images/favicon.ico">
    <%@ include file="/site/css.jsp" %>
</head>
<body>
<div id="page">
    <%@ include file="/site/header_nav.jsp" %>
    <div id="container">
        <ul id="liebiao" class="liebiao" style="float:none;margin-top:10px;">
            <c:forEach items="${dataList}" var="data" varStatus="status">
	            <li id="${data.ID}">
		            <a href="${ctx}/site/shangpin_x.jsp?id=${data.ID}">
		                <c:if test="${data.TITLE_IMG !=null && data.TITLE_IMG !=''}">
		                    <img src="${ctx}${data.TITLE_IMG}.s.jpg"/>
		                </c:if>
	                    <span style="font-weight:700;overflow:hidden;">${data.TITLE}</span>
		            	<div>
		            	    <span class="small left" style="color:red;font-weight:bold;">
		                    	￥<span style="display:inline;" id="${data.ID}_price">${data.PRICE}</span>
		            	    	<input class="text count" id="${data.ID}_count" type="text" onChange="changeCount(this,'${data.ID}')" value='<fmt:formatNumber pattern="###" value="${data.TOTAL}"/>' style="height:25px;width:40px;text-align:center;"/>
		            	    </span>
		            	    <span class="small right" style="background:url(${ctx}/site/images/delcart_16.png) no-repeat center;width:32px;height:32px;" onclick="delProduct('${data.ID}');return false;"></span>
			           	</div>
			     	</a>
		     	</li>
		    </c:forEach>		      	
        </ul>
        <div id="zongjia_txt" style="line-height: 45px;height:45px;text-align:right;font-weight:bolder;">
        </div>
        <c:if test="${productListMap !=null && productListMap!=''}">
	        <form id="add_form" action="${ctx}/site/site.action.jsp?action=saveProdOrder" method="POST">
	            <input type="hidden" id="shangpin" name="shangpin"><!--商品-->
	            <input type="hidden" id="shangpinsl" name="shangpinsl"><!--商品数量-->
	            <input type="hidden" id="shangpinjg" name="shangpinjg"><!--商品价格-->
	            <input type="hidden" id="customerId" name="customerId" value="${customer.ID}"><!--客户ID-->
	            <div class="box-btn" id="save_div">
	                <a id="save-btn" href="#" class="button big orange" onclick="saveProOrder();return false;" >结算</a>
	            </div>
	        </form>
	        <c:if test="${customer == null || customer == ''}">
                <div class="box-btn" style="display: none;" id="login_div">
                    <a href="${url}" id="login-btn" class="button big orange" >未登录，请先登录</a>
                </div>
            </c:if>
	     </c:if>
    </div>
    <%@ include file="/site/footer.jsp" %>
</div>
<%@ include file="/site/js.jsp" %>
<script src="${ctx}/site/js/jquery.form.js"></script>
<script>
    $('#add_form').ajaxForm({
        success:function(result,statusText,xhr,ele){
            if(result.isSuccess){
                appUtil.setCookie("productList","{}",{"path":"${ctx}/site"});
                appUtil.alert("保存成功！");
                $("#liebiao").html("<div style='margin-top:15px;text-align:center;font-weight:bold;'>亲，还没选购商品哦，赶紧去选购吧！</div>");
                $("#zongjia_txt").html("");
     		    $("#save_div").hide();
                window.location.href = "${ctx}/site/my_order.jsp";
            }else{
                appUtil.alert("保存失败："+result.error);
            }
        }
    });
	var cookieProStr = appUtil.getCookie("productList") || "{}";
	//隐藏订单按钮
    var productList = JSON.parse(cookieProStr);
    $(document).ready(function(){
        // 计算总价
        clacTotalPrice();
 	    //阻止冒泡事件
        $("input.count").on("click",function(e){
            if (e && e.stopPropagation) {//非IE
                e.stopPropagation();
            }else {//IE
                window.event.cancelBubble = true;
            }
            return false;
        });
 	    var url = "${url}";
 	    if(url){
 		    $("#login_div").show();
 		    $("#save_div").hide();
 		    $("#login-btn").attr("href",url);
 	    }else{
  		    $("#login_div").hide();
 		    $("#save_div").show();
 	    }
    });

    /*** 删除购物车里面的商品 ***/
    function delProduct(productId){
        delete productList[productId];
        appUtil.setCookie("productList",JSON.stringify(productList),{"path":"${ctx}/site"});
        $("#"+productId).remove();
        clacTotalPrice();
        return false;
    }

    /*** 保存购物车 ***/
    function saveProOrder(){
        var ck = appUtil.getCookie("productList");
        if(ck=='{}' || !ck){
            appUtil.alert("请选购商品！");
            return;
        }
        var shangpin = [];
        var shangpinsl = [];
        var shangpinjg = [];
        var shangpinjf = [];
        $("#liebiao").find("li").each(function(){
    		var id = $(this).attr("id");
    		var price = $("#"+id+"_price").text()||0;
    		var point = $("#"+id+"_point").text()||0;
    		var count = $("#"+id+"_count").val()||0;
    		shangpin[shangpin.length] =  id;
    		shangpinsl[shangpinsl.length] = count;
    		shangpinjg[shangpinjg.length] = price;
    		shangpinjf[shangpinjf.length] = point;
    	});
        $("#shangpin").val(shangpin.join(";"));
        $("#shangpinsl").val(shangpinsl.join(";"));
        $("#shangpinjg").val(shangpinjg.join(";"));
        $("#shangpinjf").val(shangpinjf.join(";"));
        $('#add_form').submit();
    }

    /*** 修改商品数量 ***/
    function changeCount(ele,productId){
        var eleVal = ele.value;
        if(!/^[1-9]+\d*$/.test(eleVal)){
            appUtil.alert("请输入大于零的整数!");
            ele.value = 1;
            eleVal = 1;
        }
        productList[productId] = ele.value;
        appUtil.setCookie("productList",JSON.stringify(productList),{"path":"${ctx}/site"});
        clacTotalPrice();
    }

    /*** 计算商品总价 ***/
    function clacTotalPrice(){
        var total = 0,n = 0,pTotal = 0;
		$("#liebiao").find("li").each(function(){
    		var id = $(this).attr("id");
    		var price = $("#"+id+"_price").text()||0;
    		var point = $("#"+id+"_point").text()||0;
    		var count = $("#"+id+"_count").val()||0;
    		total += price * count;
    		pTotal += point * count;
    		n++;
    	});
        $("#zongjifen").val(pTotal);
        if(n > 0){
            $("#zongjia_txt").html('商品总价：<span style="color:red;margin:0px;padding:0px;" >￥'+total.toFixed(2)+'</span>');
        }else{
            $("#liebiao").html("<div style='margin-top:15px;text-align:center;font-weight:bold;'>亲，还没选购商品哦，赶紧去选购吧！</div>");
            $("#zongjia_txt").html("");
  		    $("#login_div").hide();
 		    $("#save_div").hide();
        }
    }
</script>
</body>
</html>